<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="120px">
            <el-form-item label="描述" prop="description">
              <el-input v-model="queryParams.description" clearable placeholder="请输入描述" @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="是否删除：0-未删除，1-已删除" prop="isDeleted">-->
            <!--              <el-input v-model="queryParams.isDeleted" placeholder="请输入是否删除：0-未删除，1-已删除" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="SAP生产订单号" prop="sapOrderCode">
              <el-input v-model="queryParams.sapOrderCode" clearable placeholder="请输入SAP生产订单号"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="车厢类型" prop="carriageTypeId">
              <el-input v-model="queryParams.carriageTypeId" clearable placeholder="请输入车厢类型ID"
                @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="车厢编码" prop="carriageCode">
              <el-input v-model="queryParams.carriageCode" clearable placeholder="请输入车厢编码" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="计划开始日期" prop="planStartDate">
              <el-date-picker v-model="queryParams.planStartDate" clearable placeholder="请选择计划开始日期" type="date"
                value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="计划结束日期" prop="planEndDate">
              <el-date-picker v-model="queryParams.planEndDate" clearable placeholder="请选择计划结束日期" type="date"
                value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="实际开始日期" prop="actualStartDate">
              <el-date-picker v-model="queryParams.actualStartDate" clearable placeholder="请选择实际开始日期" type="date"
                value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="实际结束日期" prop="actualEndDate">
              <el-date-picker v-model="queryParams.actualEndDate" clearable placeholder="请选择实际结束日期" type="date"
                value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="优先级" prop="priority">
              <el-input v-model="queryParams.priority" clearable placeholder="请输入优先级" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:sapOrder:add']" icon="Plus" plain type="primary"
              @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:sapOrder:edit']" :disabled="single" icon="Edit" plain type="success"
              @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:sapOrder:remove']" :disabled="multiple" icon="Delete" plain type="danger"
              @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:sapOrder:export']" icon="Download" plain type="warning"
              @click="handleExport">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:sapOrder:bind']" icon="Link" plain type="info"
              @click="handleBindRfid">绑定标签</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['painting:sapOrder:bind']" :disabled="!hasBoundTags" icon="Unlink" plain
              type="warning" @click="handleUnbindRfid">解绑标签</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="sapOrderList" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <!-- <el-table-column v-if="true" align="center" label="主键ID" prop="id" /> -->
        <!-- ：0-禁用，1-启用 -->
        <el-table-column align="center" label="状态" prop="status">
          <template #default="scope">
            <span v-if="scope.row.status == 0">禁用</span>
            <span v-if="scope.row.status == 1">启用</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述" prop="description" />
        <!--        <el-table-column label="是否删除：0-未删除，1-已删除" align="center" prop="isDeleted" />-->
        <el-table-column align="center" label="生产订单号" prop="sapOrderCode" />
        <el-table-column align="center" label="订单类型" prop="orderType" />
        <!-- 0-未开始，1-进行中，2-已完成，3-已取消 -->
        <el-table-column align="center" label="订单状态" prop="orderStatus" >
        <template #default="scope">
            <span v-if="scope.row.orderStatus == 0">未开始</span>
            <span v-if="scope.row.orderStatus == 1">进行中</span>
            <span v-if="scope.row.orderStatus == 2">已完成</span>
            <span v-if="scope.row.orderStatus == 3">已取消</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="车厢类型" prop="carriageTypeId">
          <template #default="scope">
            <!-- <dict-tag :options="sys_device_type" :value="scope.row.deviceType" /> -->
            <dict-tag :options="carriage_code_type" :value="scope.row.carriageTypeId" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="车厢编码" prop="carriageCode" />
        <el-table-column align="center" label="计划开始日期" prop="planStartDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.planStartDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="计划结束日期" prop="planEndDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.planEndDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实际开始日期" prop="actualStartDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.actualStartDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实际结束日期" prop="actualEndDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.actualEndDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="优先级" prop="priority" />
        <el-table-column align="center" label="绑定状态" prop="bindStatus">
          <template #default="scope">
            <el-tag :type="scope.row.bindStatus === 1 ? 'success' : 'info'">
              {{ scope.row.bindStatus === 1 ? '已绑定' : '未绑定' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" prop="remark" />
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['painting:sapOrder:edit']" icon="Edit" link type="primary"
                @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['painting:sapOrder:remove']" icon="Delete" link type="primary"
                @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
        :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改SAP订单管理对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="800px">
      <el-form ref="sapOrderFormRef" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入内容" type="textarea" />
        </el-form-item>
        <!--        <el-form-item label="是否删除：0-未删除，1-已删除" prop="isDeleted">-->
        <!--          <el-input v-model="form.isDeleted" placeholder="请输入是否删除：0-未删除，1-已删除" />-->
        <!--        </el-form-item>-->
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" class="m-2" placeholder="请选择状态" size="large">
            <el-option v-for="item in optionsStatus" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="SAP生产订单号" prop="sapOrderCode">
          <el-input v-model="form.sapOrderCode" placeholder="请输入SAP生产订单号" />
        </el-form-item>
        <el-form-item label="订单类型" prop="orderType">
          <el-input v-model="form.orderType" placeholder="请输入订单类型" />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" class="m-2" placeholder="请输入订单状态" size="large">
            <el-option v-for="item in optionsOrderStatus" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <!-- <el-input v-model="form.orderStatus" placeholder="请输入订单状态：0-未开始，1-进行中，2-已完成，3-已取消" /> -->
        </el-form-item>
        <el-form-item label="车厢类型" prop="carriageTypeId">
          <el-select v-model="form.carriageTypeId" placeholder="请选择">
            <el-option v-for="dict in carriage_code_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车厢编码" prop="carriageCode">
          <el-input v-model="form.carriageCode" placeholder="请输入车厢编码" />
        </el-form-item>
        <el-form-item label="计划开始日期" prop="planStartDate">
          <el-date-picker v-model="form.planStartDate" clearable placeholder="请选择计划开始日期" type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划结束日期" prop="planEndDate">
          <el-date-picker v-model="form.planEndDate" clearable placeholder="请选择计划结束日期" type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际开始日期" prop="actualStartDate">
          <el-date-picker v-model="form.actualStartDate" clearable placeholder="请选择实际开始日期" type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际结束日期" prop="actualEndDate">
          <el-date-picker v-model="form.actualEndDate" clearable placeholder="请选择实际结束日期" type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="form.priority" :min="1"  />
          <!-- <el-input v-model="form.priority" placeholder="请输入优先级" /> -->
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- RFID标签绑定对话框 -->
    <el-dialog v-model="rfidDialog.visible" append-to-body title="选择RFID标签" width="800px">
      <el-table ref="rfidTableRef" v-loading="rfidDialog.loading" :data="rfidDialog.tagList"
        @selection-change="handleRfidSelectionChange">
        <el-table-column :selectable="isTagSelectable" align="center" type="selection" width="55" />
        <el-table-column align="center" label="标签ID" prop="id" />
        <el-table-column align="center" label="标签编码" prop="tagCode" />
        <el-table-column align="center" label="标签状态" prop="status">
          <template #default="scope">
            <el-tag :type="getTagStatusType(scope.row)">
              {{ getTagStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="绑定订单" prop="bindTargetId">
          <template #default="scope">
            <span>{{ scope.row.bindTargetId || '-' }}</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="rfidDialog.buttonLoading" type="primary" @click="submitBindRfid">确 定</el-button>
          <el-button @click="rfidDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="SapOrder" setup>
import { addSapOrder, delSapOrder, getSapOrder, listSapOrder, updateSapOrder } from '@/api/painting/sapOrder';
import { SapOrderForm, SapOrderQuery, SapOrderVO } from '@/api/painting/sapOrder/types';
import { listRfidTag } from '@/api/painting/rfidTag';
import { RfidTagVO } from '@/api/painting/rfidTag/types';
import request from '@/utils/request';
import { ref } from 'vue'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { carriage_code_type } = toRefs<any>(proxy?.useDict('carriage_code_type'));

const sapOrderList = ref<SapOrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const hasBoundTags = ref(false);
const queryFormRef = ref<ElFormInstance>();
const sapOrderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const optionsStatus = [
  {
    value: 0,
    label: '未启用',
  },
  {
    value: 1,
    label: '已启用',
  },
]
const optionsOrderStatus = [
  {
    value: 0,
    label: '未开始',
  },
  {
    value: 1,
    label: '进行中',
  }, {
    value: 2,
    label: '已完成',
  },
  {
    value: 3,
    label: '已取消',
  },
]

const rfidDialog = reactive({
  visible: false,
  loading: false,
  buttonLoading: false,
  tagList: [] as RfidTagVO[],
  selectedTags: [] as RfidTagVO[],
  currentOrderCode: ''
});

const initFormData: SapOrderForm = {
  id: undefined,
  status: undefined,
  description: undefined,
  isDeleted: undefined,
  sapOrderCode: undefined,
  orderType: undefined,
  orderStatus: undefined,
  carriageTypeId: undefined,
  carriageCode: undefined,
  planStartDate: undefined,
  planEndDate: undefined,
  actualStartDate: undefined,
  actualEndDate: undefined,
  priority: 1,
  remark: undefined
}
const data = reactive<PageData<SapOrderForm, SapOrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: undefined,
    description: undefined,
    isDeleted: undefined,
    sapOrderCode: undefined,
    orderType: undefined,
    orderStatus: undefined,
    carriageTypeId: undefined,
    carriageCode: undefined,
    planStartDate: undefined,
    planEndDate: undefined,
    actualStartDate: undefined,
    actualEndDate: undefined,
    priority: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态：0-禁用，1-启用不能为空", trigger: "change" }
    ],
    isDeleted: [
      { required: true, message: "是否删除：0-未删除，1-已删除不能为空", trigger: "blur" }
    ],
    sapOrderCode: [
      { required: true, message: "SAP生产订单号不能为空", trigger: "blur" }
    ],
    orderType: [
      { required: true, message: "订单类型不能为空", trigger: "change" }
    ],
    orderStatus: [
      { required: true, message: "订单状态：0-未开始，1-进行中，2-已完成，3-已取消不能为空", trigger: "change" }
    ],
    carriageTypeId: [
      { required: true, message: "车厢类型ID不能为空", trigger: "blur" }
    ],
    carriageCode: [
      { required: true, message: "车厢编码不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询SAP订单管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSapOrder(queryParams.value);
  sapOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  sapOrderFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: SapOrderVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;

  // 更新是否有绑定标签的状态
  if (selection.length === 1) {
    hasBoundTags.value = selection[0].bindStatus === 1;
  } else {
    hasBoundTags.value = false;
  }
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加SAP订单管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: SapOrderVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getSapOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改SAP订单管理";
}

/** 提交按钮 */
const submitForm = () => {
  sapOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateSapOrder(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addSapOrder(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: SapOrderVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除SAP订单管理编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delSapOrder(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('painting/sapOrder/export', {
    ...queryParams.value
  }, `sapOrder_${new Date().getTime()}.xlsx`)
}

/** 处理RFID标签选择变化 */
const handleRfidSelectionChange = (selection: RfidTagVO[]) => {
  rfidDialog.selectedTags = selection;
}

/** 判断标签是否可选 */
const isTagSelectable = (row: RfidTagVO) => {
  // 如果标签未绑定，或者已绑定到当前选中的订单，则可以选择
  return !row.bindTargetId || row.bindTargetId === rfidDialog.currentOrderCode;
}

/** 获取标签状态类型 */
const getTagStatusType = (row: RfidTagVO) => {
  if (row.bindTargetId === rfidDialog.currentOrderCode) {
    return 'success';
  } else if (row.bindTargetId) {
    return 'danger';
  }
  return 'info';
}

/** 获取标签状态文本 */
const getTagStatusText = (row: RfidTagVO) => {
  if (row.bindTargetId === rfidDialog.currentOrderCode) {
    return '已绑定当前订单';
  } else if (row.bindTargetId) {
    return '已绑定其他订单';
  }
  return '可用';
}

/** 打开RFID标签绑定对话框 */
const handleBindRfid = async () => {
  if (ids.value.length !== 1) {
    proxy?.$modal.msgWarning("请选择一条SAP订单进行标签绑定");
    return;
  }

  const selectedOrder = sapOrderList.value.find(order => order.id === ids.value[0]);
  if (!selectedOrder) {
    proxy?.$modal.msgError("未找到选中的SAP订单");
    return;
  }

  rfidDialog.currentOrderCode = selectedOrder.sapOrderCode;
  rfidDialog.visible = true;
  rfidDialog.loading = true;
  try {
    const res = await listRfidTag({
      pageNum: 1,
      pageSize: 100,
      status: 1
    }); // 获取所有标签，包括已绑定的
    rfidDialog.tagList = res.rows;

    // 在下一个tick中设置选中状态
    nextTick(() => {
      const rfidTableRef = proxy?.$refs.rfidTableRef as any;
      if (rfidTableRef) {
        // 清除之前的选择
        rfidTableRef.clearSelection();
        // 选中已绑定到当前订单的标签
        rfidDialog.tagList.forEach((tag, index) => {
          if (tag.bindTargetId === rfidDialog.currentOrderCode) {
            rfidTableRef.toggleRowSelection(tag, true);
          }
        });
      }
    });
  } catch (error) {
    proxy?.$modal.msgError("获取RFID标签列表失败");
  } finally {
    rfidDialog.loading = false;
  }
}

/** 提交RFID标签绑定 */
const submitBindRfid = async () => {
  if (rfidDialog.selectedTags.length === 0) {
    proxy?.$modal.msgWarning("请选择要绑定的RFID标签");
    return;
  }

  rfidDialog.buttonLoading = true;
  try {
    const selectedOrder = sapOrderList.value.find(order => order.id === ids.value[0]);
    if (!selectedOrder) {
      proxy?.$modal.msgError("未找到选中的SAP订单");
      return;
    }

    await request.post('/painting/sapOrder/bindRfid', {
      sapOrderCode: selectedOrder.sapOrderCode,
      rfidTags: rfidDialog.selectedTags.map(tag => tag.id)
    });
    proxy?.$modal.msgSuccess("绑定成功");
    rfidDialog.visible = false;
    await getList();
  } catch (error) {
    proxy?.$modal.msgError("绑定失败");
  } finally {
    rfidDialog.buttonLoading = false;
  }
}

/** 处理解绑标签 */
const handleUnbindRfid = async () => {
  if (ids.value.length !== 1) {
    proxy?.$modal.msgWarning("请选择一条SAP订单进行标签解绑");
    return;
  }

  const selectedOrder = sapOrderList.value.find(order => order.id === ids.value[0]);
  if (!selectedOrder) {
    proxy?.$modal.msgError("未找到选中的SAP订单");
    return;
  }

  try {
    await proxy?.$modal.confirm('是否确认解绑该订单的所有标签？');
    await request.post('/painting/sapOrder/unbindRfid', {
      sapOrderCode: selectedOrder.sapOrderCode
    });
    proxy?.$modal.msgSuccess("解绑成功");
    await getList();
  } catch (error) {
    if (error !== 'cancel') {
      proxy?.$modal.msgError("解绑失败");
    }
  }
}

onMounted(() => {
  getList();
});
</script>
